<template>
  <div class="js-area-cascader">
    <el-cascader
      popper-class="myCascader"
      ref="jsCascaderRef"
      v-model="selectedArea"
      :options="areaOptions"
      :props="cascaderProps"
      placeholder="选择市-区-镇"
      clearable
      size="medium"
      @change="handleAreaChange"
      style="width: 100%"
    >      
    </el-cascader>
  </div>
</template>

<script>
export default {
  name: "JiangsuAreaCascader",
  props: {
    defaultSelected: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      selectedArea: [], // 存储格式：[省ID, 市ID, 区ID, 镇ID]
      areaOptions: [],
      cascaderProps: {
        lazy: true,
        lazyLoad: this.loadChildData,
        checkStrictly: true, // 允许自由选择层级，避免默认勾选逻辑干扰
        label: "nodeText",
        value: "nodeId",
        children: "children",
        loadingIcon: "el-icon-loading",
        expandTrigger: "hover",
        valueFormat: "value",
        // 关键：关闭默认勾选状态的自动同步，避免与自定义单选框冲突
        emitPath: false
      }
    };
  },
  watch: {
    defaultSelected: {
      immediate: true,
      handler(newVal) {
        // 补全省ID用于内部层级加载，外部无需关心
        this.selectedArea = newVal.length ? ["320000", ...newVal] : ["320000"];
      }
    }
  },
  mounted() {
    this.initProvinceData();
    this.$nextTick(() => this.expandProvinceNode());
  },
  methods: {
    // 1. 初始化省级数据（仅江苏省，level=0）
    initProvinceData() {
      setTimeout(() => {
        this.areaOptions = [
          {
            nodeId: "320000",
            nodeText: "江苏省",
            hasChildren: true,
            level: 0,
            // 显式关闭默认勾选框（关键）
            checkable: false
          }
        ];
        this.$forceUpdate();
      }, 300);
    },

    // 2. 懒加载子级数据（市→区→镇）
    loadChildData(node, resolve) {
      const parentId = node.value || node.nodeId;
      node.loading = true;

      setTimeout(() => {
        let childData = [];

        // 省（320000）→ 市（level=1）
        if (parentId === "320000") {
          childData = [
            { nodeId: "320100", nodeText: "南京市", hasChildren: true, level: 1, checkable: false },
            { nodeId: "320200", nodeText: "无锡市", hasChildren: true, level: 1, checkable: false },
            { nodeId: "320300", nodeText: "徐州市", hasChildren: true, level: 1, checkable: false },
            { nodeId: "320400", nodeText: "常州市", hasChildren: true, level: 1, checkable: false },
            { nodeId: "320500", nodeText: "苏州市", hasChildren: true, level: 1, checkable: false },
            { nodeId: "320600", nodeText: "南通市", hasChildren: true, level: 1, checkable: false },
            { nodeId: "320700", nodeText: "连云港市", hasChildren: true, level: 1, checkable: false },
            { nodeId: "320800", nodeText: "淮安市", hasChildren: true, level: 1, checkable: false },
            { nodeId: "320900", nodeText: "盐城市", hasChildren: true, level: 1, checkable: false },
            { nodeId: "321000", nodeText: "扬州市", hasChildren: true, level: 1, checkable: false },
            { nodeId: "321100", nodeText: "镇江市", hasChildren: true, level: 1, checkable: false },
            { nodeId: "321200", nodeText: "泰州市", hasChildren: true, level: 1, checkable: false },
            { nodeId: "321300", nodeText: "宿迁市", hasChildren: true, level: 1, checkable: false }
          ];
        }

        // 南京（320100）→ 区（level=2）
        else if (parentId === "320100") {
          childData = [
            { nodeId: "320102", nodeText: "玄武区", hasChildren: true, level: 2, checkable: false },
            { nodeId: "320104", nodeText: "秦淮区", hasChildren: true, level: 2, checkable: false },
            { nodeId: "320105", nodeText: "建邺区", hasChildren: true, level: 2, checkable: false },
            { nodeId: "320106", nodeText: "鼓楼区", hasChildren: true, level: 2, checkable: false },
            { nodeId: "320111", nodeText: "浦口区", hasChildren: true, level: 2, checkable: false }
          ];
        }

        // 玄武区（320102）→ 镇（level=3）
        else if (parentId === "320102") {
          childData = [
            { nodeId: "320102001", nodeText: "梅园新村街道", hasChildren: false, level: 3, checkable: false },
            { nodeId: "320102002", nodeText: "新街口街道", hasChildren: false, level: 3, checkable: false },
            { nodeId: "320102003", nodeText: "玄武门街道", hasChildren: false, level: 3, checkable: false }
          ];
        }

        // 苏州（320500）→ 区（level=2）
        else if (parentId === "320500") {
          childData = [
            { nodeId: "320505", nodeText: "虎丘区", hasChildren: true, level: 2, checkable: false },
            { nodeId: "320506", nodeText: "吴中区", hasChildren: true, level: 2, checkable: false },
            { nodeId: "320583", nodeText: "昆山市", hasChildren: true, level: 2, checkable: false }
          ];
        }

        // 昆山市（320583）→ 镇（level=3）
        else if (parentId === "320583") {
          childData = [
            { nodeId: "320583100", nodeText: "玉山镇", hasChildren: false, level: 3, checkable: false },
            { nodeId: "320583101", nodeText: "巴城镇", hasChildren: false, level: 3, checkable: false }
          ];
        }

        // 补全children属性，确保组件正常识别子级
        childData = childData.map(item => ({
          ...item,
          children: item.hasChildren ? [] : null
        }));

        resolve(childData);
        node.loading = false;
      }, 400);
    },

    // 3. 自动展开省级节点（用户直接看到市级列表）
    expandProvinceNode() {
      const cascader = this.$refs.jsCascaderRef;
      if (cascader?.panel) {
        const provinceNode = cascader.panel.nodes.find(n => n.value === "320000");
        if (provinceNode && !provinceNode.expanded) {
          provinceNode.expand();
        }
      }
    },

    // 4. 判断节点是否被选中（控制自定义单选框的选中状态）
    isNodeSelected(node) {
      // 根据层级匹配selectedArea中的对应位置：市→索引1，区→索引2，镇→索引3
      const levelMap = { 1: 1, 2: 2, 3: 3 };
      const targetIndex = levelMap[node.level];
      return targetIndex !== undefined && this.selectedArea[targetIndex] === node.value;
    },

    // 5. 点击自定义单选框的逻辑（更新选中状态）
    handleRadioClick(node) {
      const newSelected = [...this.selectedArea];
      // 根据层级更新selectedArea：市→更新索引1，区→更新索引2，镇→更新索引3
      switch (node.level) {
        case 1: // 选中市：清空后续的区、镇
          newSelected[1] = node.value;
          newSelected.splice(2, 2); // 删除索引2（区）、3（镇）
          break;
        case 2: // 选中区：清空后续的镇
          newSelected[2] = node.value;
          newSelected.splice(3, 1); // 删除索引3（镇）
          break;
        case 3: // 选中镇：直接赋值
          newSelected[3] = node.value;
          break;
      }
      this.selectedArea = newSelected;
      // 触发change事件，对外暴露过滤后的值
      this.handleAreaChange(newSelected);
    },

    // 6. 对外暴露选中值（过滤省ID，只传市-区-镇）
    handleAreaChange(val) {
      const result = val.length > 1 ? val.slice(1) : [];
      this.$emit("areaChange", result);
    }
  }
};
</script>

<style scoped>
.js-area-cascader {
  max-width: 500px;
}



</style>